package com.autonomous_printer.impl;

import com.autonomous_printer.mapper.FileMapper;
import com.autonomous_printer.pojo.File;
import com.autonomous_printer.service.FileService;
import com.autonomous_printer.util.ConvertToPDFUtil;
import com.lowagie.text.pdf.PdfReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    FileMapper fileMapper;

    @Autowired
    ConvertToPDFUtil convertToPDF;

    @Override
    public int upload(File file, InputStream fileSteam) throws IOException {
        FileOutputStream outputStream = new FileOutputStream(file.getFileLie());
        try {
            byte[] data = new byte[1024];
            int len = -1;
            for (; (len = fileSteam.read(data)) != -1; ) {
                outputStream.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
        fileMapper.insertFile(file);
        return file.getId();
    }

    @Override
    public String convertToPDF(String filepath) {
        int index = filepath.lastIndexOf('.');
        String substring = filepath.substring(index);
        String ans = filepath.substring(0, index) + ".pdf";
        if (".doc".equals(substring)) {
            try {
                convertToPDF.WordToPDF(filepath, ans);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ans = ans.substring(7);
        return ans;
    }

    @Override
    public int getPdfPage(String filepath) {
        int pageCount = 0;
        PdfReader reader;
        try {
            reader = new PdfReader(filepath);
            pageCount = reader.getNumberOfPages();
        } catch (IOException e) {
            return pageCount;
        }
        return pageCount;
    }
}
